package cn.tedu.vrd.controller;

import cn.tedu.vrd.mapper.UserMapper;
import cn.tedu.vrd.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, HttpSession session, String rem, HttpServletResponse response){
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //把登陆成功时的用户信息保存到会话对象中
                session.setAttribute("u",u);//不能写user，因为user只传入了账号和密码，u则通过UserMapper查询到所有信息
                //创建Cookie并把用户名和密码保存进Cookie
                Cookie c1 = new Cookie("un",u.getUsername());
                Cookie c2 = new Cookie("pw",u.getPassword());
                //设置保存时间
                c1.setMaxAge(60*60*24*30);
                c2.setMaxAge(60*60*24*30);
                //通过相应对象将Cookie发送给客户端
                response.addCookie(c1);
                response.addCookie(c2);
                return 1;//登陆成功
            }
            return 3;//密码错误
        }
        return 2;//用户不存在
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User) session.getAttribute("u");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("u");
    }
}
